package hlhj.fhp.checkpoint.fgms

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Handler
import android.os.Message
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.GridLayout
import android.widget.ImageView
import android.widget.RadioButton
import android.widget.RelativeLayout
import com.bumptech.glide.Glide
import com.example.mymvp.log
import com.example.mymvp.mvp.BaseFgm
import com.google.gson.Gson
import com.makeramen.roundedimageview.RoundedImageView
import ezy.ui.view.BannerView
import hlhj.fhp.checkpoint.Constant
import hlhj.fhp.checkpoint.R
import hlhj.fhp.checkpoint.adp.HomePointPageAdp
import hlhj.fhp.checkpoint.atys.CarCheckAty
import hlhj.fhp.checkpoint.atys.CheckInfoAty
import hlhj.fhp.checkpoint.atys.NoticeDetailAty
import hlhj.fhp.checkpoint.customView.ServerPop
import hlhj.fhp.checkpoint.http.Urls
import hlhj.fhp.checkpoint.iview.ActiveView
import hlhj.fhp.checkpoint.iview.HomeView
import hlhj.fhp.checkpoint.javaBean.*
import hlhj.fhp.checkpoint.presenter.HomePresenter
import hlhj.fhp.checkpoint.utils.GlideUtils
import hlhj.fhp.checkpoint.utils.ToastUtils
import kotlinx.android.synthetic.main.fgm_home.*
import kotlinx.android.synthetic.main.fgm_home.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import com.alipay.sdk.app.PayTask
import hlhj.fhp.checkpoint.atys.PayAty


/**
 * Created by Never Fear   on 2018\11\6 0006.
Never More....
 */
class HomeFgm :BaseFgm<HomeView,HomePresenter>(), HomeView, ActiveView {
    private var serverPop:ServerPop?=null
    private var homePointPageAdp :HomePointPageAdp?=null
    private val fgmLists=ArrayList<Fragment>()
    override fun setDelete(myBaseBean: MyBaseBean) {
        ToastUtils.toast("删除成功",context!!)
        presenter?.getCarPages(context!!)
    }
    override fun setContact(serventBean: ServentBean) {
        serverPop?.setDatas(serventBean.info as ArrayList<ServentBean.InfoBean>)
        log("fhp","算了-------${serverPop==null}---")
        serverPop?.let {
            if (it.isShowing){
                it.dismiss()
            }else{
                log("fhp","算了----------")
                it.showAtLocation(rootView.father,Gravity.CENTER,0,0)
                val lp = activity?.window?.attributes
                lp!!.alpha=0.5f
                activity?.window?.attributes=lp
            }
        }
    }

    //违章车
    override fun setCarPages(carPageBean: CarPageBean) {
        Log.e("fhp","那到这了么？")
        try {
            rootView.carViewPager.visibility=View.VISIBLE
            rootView.pageRg.visibility=View.VISIBLE
            fgmLists.clear()
            homePointPageAdp?.notifyDataSetChanged()
            when(carPageBean.info.size){
                3->{
                    rootView.pageRg.getChildAt(2).visibility=View.VISIBLE
                    rootView.pageRg.getChildAt(1).visibility=View.VISIBLE

                }
                2->{
                    rootView.pageRg.getChildAt(1).visibility=View.VISIBLE
                }
                1->{
//                    rootView.pageRg.removeViewAt(2)
                    rootView.pageRg.getChildAt(2).visibility=View.GONE
                }
                0->{
//                    rootView.pageRg.removeViewAt(2)
//                    rootView.pageRg.removeViewAt(1)
                    rootView.pageRg.getChildAt(2).visibility=View.GONE

                    rootView.pageRg.getChildAt(1).visibility=View.GONE

                }
            }
            if (carPageBean.info.size>0){
                if (carPageBean.info.size<3){
                    carPageBean.info.forEachIndexed { index, infoBean ->
                        fgmLists.add(CarPageFgm.getInstance(0,Gson().toJson(infoBean)))
//                        homePointPageAdp?.notifyDataSetChanged()
                    }
                    fgmLists.add(CarPageFgm.getInstance(1,""))
//                    homePointPageAdp?.notifyDataSetChanged()
                }else{
                    carPageBean.info.forEachIndexed { index, infoBean ->
                        fgmLists.add(CarPageFgm.getInstance(0,Gson().toJson(infoBean)))
//                        homePointPageAdp?.notifyDataSetChanged()
                    }
                }
                val button = rootView.pageRg.getChildAt(0) as RadioButton
                button.isChecked=true
            }else if (carPageBean.info.size==0){
                fgmLists.add(CarPageFgm.getInstance(1,""))
//                homePointPageAdp?.notifyDataSetChanged()
                rootView.pageRg.visibility=View.GONE
            }
            homePointPageAdp= HomePointPageAdp(fgmLists,childFragmentManager)
            rootView.carViewPager.adapter=homePointPageAdp
            rootView.carViewPager.offscreenPageLimit=5
        }catch (e:Exception){
            e.printStackTrace()
            Log.e("fhp","错误了${e.toString()}")
        }

    }
    //公告
    override fun setNotice(noticeBean: NoticeBean) {
        val textLists=ArrayList<String>()
        noticeBean.info.forEachIndexed { index, infoBean ->
            textLists.add(infoBean.title)
        }
        noticeText.setTextList(textLists)
        noticeText.setText(15f,0,Color.parseColor("#333333"))
        noticeText.setAnimTime(200)
        noticeText.setTextStillTime(3000)
        noticeText.startAutoScroll()
        noticeText.setOnItemClickListener {
            p->
           val i = Intent(context,NoticeDetailAty::class.java)
            i.putExtra("id",noticeBean.info[p].id)
            startActivity(i)
        }
    }
    //轮播
    override fun setBanner(bannerBean: BannerBean) {
        try {
            val bannerView = rootView.findViewById<BannerView<BannerBean.InfoBean>>(R.id.banner)
//            val bannerView = banner as BannerView<BannerBean.InfoBean>
            bannerView.setViewFactory { item, position, container ->
                val root= LayoutInflater.from(container.context).inflate(R.layout.banner_item,null) as View
                val imageView = root.findViewById<RoundedImageView>(R.id.itemImg)
                imageView.scaleType=ImageView.ScaleType.FIT_XY
                Glide.with(context).load(Urls.ImgUrl+"/"+bannerBean.info[position].image).apply(GlideUtils.loadBannerOption()!!).into(imageView)
                root
            }
            bannerView.setDataList(bannerBean.info)
            bannerView.start()
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    override fun initView() {
        serverPop= ServerPop(context!!)
    }
    open fun refreshPage(){
        log("fhp","调用刷新了嘛")
        fgmLists.clear()
        homePointPageAdp= HomePointPageAdp(fgmLists,childFragmentManager)
        rootView.carViewPager.adapter=homePointPageAdp
        presenter?.getCarPages(context!!)
    }
    override fun logicStart() {
        presenter?.getbanner(context!!)
        presenter?.getNotices(context!!)
        presenter?.getCarPages(context!!)
    }

    override fun setListener() {
        rootView.btCheDai.setOnClickListener {
            val uri = Uri.parse(Constant.marketUrl)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }
        rootView.btYouka.setOnClickListener {
            ToastUtils.toast("暂未开通",context!!)
        }
        rootView.btSave.setOnClickListener {
            ToastUtils.toast("暂未开通",context!!)
        }

        serverPop?.let {
            it.setOnDismissListener {
                val lp = activity?.window?.attributes
                lp!!.alpha=1f
                activity?.window?.attributes=lp
            }
        }

        rootView.btServer.setOnClickListener {
            presenter?.getContact(context!!)

        }
        rootView.btInfo.setOnClickListener {

            val intent = Intent(context, CheckInfoAty::class.java)
            startActivity(intent)
        }
        rootView.carViewPager.addOnPageChangeListener(object :ViewPager.OnPageChangeListener{
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            }

            override fun onPageSelected(position: Int) {
                val button = rootView.pageRg.getChildAt(position) as RadioButton
                button.isChecked=true
            }
        })

        rootView.btCheck.setOnClickListener {
            if (!Constant.isActive){
                ToastUtils.toast("前去激活用户",context!!)
                val intent = Intent(context, PayAty::class.java)
                intent.putExtra("id","")
                intent.putExtra("money",Constant.Active_Money)
                intent.putExtra("orderType",2)
                startActivity(intent)

            }else{
                val intent = Intent(context, CarCheckAty::class.java)
                startActivity(intent)
            }

        }
    }

    private val SDK_PAY_FLAG: Int=1101
    private val mHandler= @SuppressLint("HandlerLeak")
    object :Handler(){
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            val result = msg!!.obj as Map<String, String>
            log("fhp","回调为${result.toString()}")
            val status = result["resultStatus"]
            ToastUtils.toast("支付成功",context!!)
            if (status.equals("9000")){
                Constant.isActive=true
            }else{

            }
        }
    }
    override fun setActiveOrderSign(beanStr: String) {
        val payBean = Gson().fromJson(beanStr, AliPayBean::class.java)
        val orderInfo = payBean.info   // 订单信息

        val payRunnable = Runnable {
            val alipay = PayTask(activity!!)
            val result = alipay.payV2(orderInfo, true)

            val msg = Message()
            msg.what = SDK_PAY_FLAG
            msg.obj = result
            mHandler.sendMessage(msg)
        }
        // 必须异步调用
        val payThread = Thread(payRunnable)
        payThread.start()
    }

    override fun bindView(): HomeView {
        return  this
    }

    override fun createPresenter(): HomePresenter {

        return HomePresenter()
    }

    override fun doBeforInit() {
        EventBus.getDefault().register(this)

    }

    @SuppressLint("MissingSuperCall")
    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }
    override fun getContentId(): Int {
        return R.layout.fgm_home
    }
    private val ADDCAR: Int = 11

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode!=-1)return
        when(requestCode){
            ADDCAR->{

            }
        }
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    fun deleteCar(deleteCarEvent: DeleteCarEvent){
        presenter?.deletCar(deleteCarEvent.id!!,context!!)
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    fun RefreshCarPage(deleteCarEvent: RefreshCarEvent){
        presenter?.getCarPages(context!!)
    }
}